package cn.zmit.kuxi.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.alipay.PayResult;
import cn.zmit.kuxi.alipay.SignUtils;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.engine.CommonFunctions;
import cn.zmit.kuxi.entity.ShoppingCartsEntity;
import cn.zmit.kuxi.event.EventFactory;
import cn.zmit.kuxi.holder.ShoppingCartsHorlder;
import cn.zmit.kuxi.interfaces.OnCartsAddNumListener;
import cn.zmit.kuxi.interfaces.OnItemSelectListener;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.widget.CheckBoxWithListVview;
import cn.zmit.kuxi.widget.CheckBoxWithListVview.OnCheckedChangeListener;
import cn.zmit.kuxi.widget.PtrHeader;

import com.alipay.sdk.app.PayTask;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.holder.ListViewDataAdapter;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;
import com.xdroid.widget.ptr.PtrDefaultHandler;
import com.xdroid.widget.ptr.PtrFrameLayout;
import com.xdroid.widget.ptr.PtrHandler;

/** * @author @parameter * @return */
public class ShoppingCartsActivity extends BaseActivity implements
		OnCheckedChangeListener, OnItemSelectListener<ShoppingCartsEntity> {
	@ViewInject(R.id.ll_unlogin)
	private LinearLayout ll_unlogin;// 未登陆
	@ViewInject(R.id.btn_cart_login)
	private Button btn_cart_login;
	@ViewInject(R.id.ll_no_products)
	private LinearLayout ll_no_products;
	@ViewInject(R.id.btn_go_to_shopping)
	private Button btn_go_to_shopping;
	@ViewInject(R.id.ll_have_products)
	private LinearLayout ll_have_products;
	@ViewInject(R.id.ptr_view_cart)
	private PtrFrameLayout ptr_view_cart;
	@ViewInject(R.id.lv_cart)
	private ListView lv_cart;

	// check intalled app
	public Boolean isInstalled(Context context) {
		PackageManager pm = getPackageManager();
		List<PackageInfo> infos = pm.getInstalledPackages(0);
		for (PackageInfo info : infos) {
			if (info.packageName.equals("com.eg.android.AlipayGphone")) {
				return true;
			}
		}
		return false;
	}

	// 支付宝支付功能

	// 复制到支付的页面，购物车点击提交的页面

	// 商户PID
	public static final String PARTNER = "2088611733777860";
	// 商户收款账号
	public static final String SELLER = "18655386599@163.com";
	// 商户私钥，pkcs8格式

	public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAORKbnGihXbb6eneu7mw7O82T46dgpwUqJtMZeppp7lQJK93UALMokKKLO7VeeC+C5UpHtd8pNMzM+LCw8Bs7rCH+JaQLGsTgY/l +TZEPv6eZoifhcbeyA5VZhF4pblYTAJfd8GgKkFiqSC6QeAAwA5gYQLXuwQZjDmEy6e7r6mBAgMBAAECgYA/dr2rU3384/fsLyJK5feILLYDNKB5mXih66QtfX/GEZSRPv78OD0neFgzcR83rj10EwFi8GC14fcbo/9dQCs +W57SYJVtrZLjCv7BQEYW66LVhSHyJ66IQnkQdh3ejqew4N3CwQ2CgJDsFJRNPg +ceP91Tev9+b7t06xqTrRQbQJBAPqQnoXDJsyLGPd0vBe2tENx7RmcWRJ2TKPz4DCXeFBGjGNc8tl9yklgybrXE61sqKRc1QGPLtxtNpXA9B7iKOcCQQDpPh/QaQnIIMrY9zdm5YSS06e0vPd2rmlWtmX1BajDs1oSNmGy3ysfXF4rvll3IWU/hej +foMVrjpbhzlklsVXAkEAuLeIxd+6aKxauYLLb0f32IjSXEEQwTWJBo0xR2FDBxsbP900AvZi/Hln/l+0V/N018bAGSgvSb0RspDO5z2fHQJBAN6u61zlC +vAMyqWTJS2yK4N2W3bhEARII0jM5CNSKUfVP1SYlCOdPNKErac03nDrpDJXrurOae3YgwEvKzmrZ0CQHPCe0V0mhIbgRceSCvbo8xXr3Up707gQ3wiSByufYTIKyDCWxec6FRUzx4jk82cVWoT+jTK26mqJprIcrsQMiw=";

	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(ShoppingCartsActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(ShoppingCartsActivity.this,
							PayFinishActivity.class);
					startActivity(intent);
					EventFactory.sendUpdateCartCount(0);

				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(ShoppingCartsActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(ShoppingCartsActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();

					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(ShoppingCartsActivity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(String price, String order_id) {
		// 订单
		String orderInfo = getOrderInfo("酷喜乐购", "酷喜商品", price, order_id);

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(ShoppingCartsActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(ShoppingCartsActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();
				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price,
			String order_id) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + order_id + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\""
				+ "http://www.aikuxi.com/api/alipay/callback" + "\"";// homer发过来

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

	// ////////////////////////////////////////////////////////////////////////////////////////////

	/**
	 * 刷新头
	 */
	private PtrHeader ptrHeader;

	@ViewInject(R.id.rl_edit_mode)
	private RelativeLayout rl_edit_mode;
	@ViewInject(R.id.rl_1)
	private RelativeLayout rl_1;
	@ViewInject(R.id.cb_select_all_edit)
	private CheckBoxWithListVview mEditSelectAll;
	@ViewInject(R.id.rl_cart_delete)
	private RelativeLayout rl_cart_delete;
	@ViewInject(R.id.rl_common_mode)
	private RelativeLayout rl_common_mode;
	@ViewInject(R.id.cb_selete_all)
	private CheckBoxWithListVview mSelectAll;
	@ViewInject(R.id.tv_goods_num)
	private TextView tv_goods_num;
	@ViewInject(R.id.tv_all_money)
	private TextView tv_all_money;
	@ViewInject(R.id.btn_settle)
	private Button btn_settle;
	String userid = null;
	private JSONArray jsonArray = null;
	private JSONArray jsonArrayDelete = null;
	private JSONArray jsonArrayAdd = null;
	private ListViewDataAdapter<ShoppingCartsEntity> shoppingAdapter;
	/**
	 * 列表选中的集合
	 * 
	 */
	public static List<ShoppingCartsEntity> mSelectItemList = new ArrayList<ShoppingCartsEntity>();

	/**
	 * 列表所有数据集合
	 */
	private TextView mEditModeTextView;

	public static List<ShoppingCartsEntity> allCartsDataList = new ArrayList<ShoppingCartsEntity>();

	public int count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		View view = initTitleBar();
		setTitleView(view);

		setContentView(R.layout.activity_shoppingcats);
		ViewUtils.inject(this);
		// jsonArray = new JSONArray();
		jsonArrayDelete = new JSONArray();
		initView();
		hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			ll_have_products.setVisibility(View.VISIBLE);
			initPtr();
		} else {
			ll_no_products.setVisibility(View.VISIBLE);
			ll_have_products.setVisibility(View.INVISIBLE);
		}

		initListView();

	}

	/**
	 * 初始化titlebar
	 */
	private View initTitleBar() {
		View view = View.inflate(context, R.layout.view_cart_titlebar, null);
		mEditModeTextView = (TextView) view.findViewById(R.id.tv_edit);
		mEditModeTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toggleEditMode();
			}
		});
		return view;
	}

	/**
	 * 编辑模式开关
	 */
	private void toggleEditMode() {
		if (mEditModeTextView.getText().toString().trim().equals("编辑")) {
			Constants.TYPE = 1;
			shoppingAdapter.notifyDataSetChanged();
			getCartsData();
			initListView();

			mEditModeTextView.setText("完成");

			CommonFunctions.getInstance().setAlphaAnim(rl_common_mode,
					rl_edit_mode);

		} else if (mEditModeTextView.getText().toString().trim().equals("完成")) {
			Constants.TYPE = 0;
			shoppingAdapter.notifyDataSetChanged();
			getCartsData();
			initListView();
			mEditModeTextView.setText("编辑");

			CommonFunctions.getInstance().setAlphaAnim(rl_edit_mode,
					rl_common_mode);
		}
	}

	/**
	 * 获取购物车数据
	 * 
	 * @param v
	 */

	public void getCartsData() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("user_id", userid);
		RequestTask.getInstance().doShoppingCarts(ShoppingCartsActivity.this,
				map, new onRequestListener());
	}

	@OnClick({ R.id.btn_cart_login, R.id.btn_go_to_shopping,
			R.id.rl_cart_delete, R.id.btn_settle })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.btn_cart_login:// 登陆
			openActivity(LoginActivity.class);
			break;
		case R.id.btn_go_to_shopping:// 打开商品栏
			if (hasLog) {
				openActivity(GoodsActivity.class);
			} else {
				openActivity(LoginActivity.class);
			}

			break;
		case R.id.rl_cart_delete:// 删除
			if (mSelectItemList.size() <= 0) {
				ToastUtils.show(context, "请选择要删除的商品");
				return;
			}

			Map<String, Object> map2 = new HashMap<String, Object>();
			map2.put("user_id", userid);
			map2.put("goods_list", jsonArrayDelete.toString());
			RequestTask.getInstance().doDeleteGoods(this, map2,
					new onDeleteRequestListener());
			mEditModeTextView.setText("完成");
			toggleEditMode();

			break;
		case R.id.btn_settle:// 提交
			if (jsonArray != null && jsonArray.length() > 0) {
				type = 0;
				// dialog
				AlertDialog.Builder builder = new AlertDialog.Builder(
						ShoppingCartsActivity.this);
				builder.setTitle("请选择支付方式");
				final String[] pay = { "支付宝", "酷币" };
				// 设置一个单项选择下拉框
				/**
				 * the first parameter is the list of singlechoiceitems,the
				 * second parameter is the index of default choice the third
				 * parameter is the listenter
				 * 
				 * @author Joash_Yan
				 */
				builder.setSingleChoiceItems(pay, 0,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Toast.makeText(ShoppingCartsActivity.this,
										"使用：" + pay[which], Toast.LENGTH_SHORT)
										.show();
								type = which;
								Log.e("which===", which + "");
							}
						});
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// alipay or kubi
								Log.e("onclick", "onclick");
								Map<String, Object> map = new HashMap<String, Object>();
								map.put("user_id", userid);
								map.put("goods_list", jsonArray.toString());
								map.put("type", type + 1 + "");
								Log.e("map===", map + "");
								RequestTask.getInstance().doCartsCommitGoods(
										ShoppingCartsActivity.this, map,
										new CommitGoodsonRequestListener());
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
				builder.show();

			} else {
				ToastUtils.show(context, "您未选择商品");
			}

			break;
		default:
			break;
		}
	}

	// 删除商品
	private class onDeleteRequestListener extends
			OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			String data = jsonData.optString("code");
			if (data != null && data.equals("1")) {
				shoppingAdapter.remove(mSelectItemList);
				clearSelectList();
				getCartsData();
				jsonArrayDelete = null;
				int count = jsonData.optInt("my_goods_count");
				EventFactory.sendUpdateCartCount(count);
				mEditModeTextView.setText("编辑");
				ToastUtils.show(context, "商品已删除");
			} else {
				ToastUtils.show(context, "删除失败");
			}
		}
	}

	private int type = 0;

	private class CommitGoodsonRequestListener extends
			OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			// TODO Auto-generated method stub
			super.onDone(request, response, dataType);
			final JsonData jsonData = JsonData.create(response);
			final String code = jsonData.optString("code");
			int amount = jsonData.optInt("amount");
			final String order_no = jsonData.optString("order_no");

			// 商品不足
			if (code.equals("0")) {
				Toast.makeText(ShoppingCartsActivity.this,
						jsonData.optString("message"), 0).show();
			}
			// aliay success
			if (code.equals("1")) {
				Toast.makeText(ShoppingCartsActivity.this,
						jsonData.optString("message"), 0).show();
				if (isInstalled(context)) {

					pay(amount + "", order_no);
				} else {
					Toast.makeText(context, "请先安装支付宝", 0).show();
				}

			}

			// 酷币不足
			if (code.equals("2")) {
				Toast.makeText(ShoppingCartsActivity.this,
						jsonData.optString("message"), 0).show();
			}
			// 酷币支付成功
			if (code.equals("3")) {
				Toast.makeText(ShoppingCartsActivity.this,
						jsonData.optString("message"), 0).show();
				Intent intent = new Intent(ShoppingCartsActivity.this,
						PayFinishActivity.class);
				startActivity(intent);
				EventFactory.sendUpdateCartCount(0);
			}

		}
	}

	/**
	 * 初始化view
	 */
	int goodsNum;
	private Boolean hasLog;

	private void initListView() {
		shoppingAdapter = new ListViewDataAdapter<ShoppingCartsEntity>();
		shoppingAdapter.setViewHolderClass(this, ShoppingCartsHorlder.class);
		ShoppingCartsHorlder.setOnItemSelectListener(this);
		ShoppingCartsHorlder
				.setListener(new OnCartsAddNumListener<ShoppingCartsEntity>() {

					@Override
					public void onlistItemSelect(int position,
							ShoppingCartsEntity itemData, int num) {
						Map<String, Object> map = new HashMap<String, Object>();
						int gp_id = Integer.parseInt(itemData.getGp_id());
						int id = Integer.parseInt(userid);
						goodsNum = num;
						map.put("gp_id", itemData.getGp_id());
						map.put("user_id", id + "");
						map.put("portion", num + "");
						RequestTask.getInstance().doAdd(
								ShoppingCartsActivity.this, map,
								new onAddRequestListener());
					}
				});
		lv_cart.setAdapter(shoppingAdapter);
	}

	/**
	 * 
	 * @author 陈旭
	 * 
	 *         2015年9月3日
	 */
	private class onAddRequestListener extends OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			String data = jsonData.optString("code");
			if (data != null && data.equals("0")) {
				// ShoppingCartsHorlder.count.setText(goodsNum+"");
				getCartsData();
				// ToastUtils.show(context, jsonData.optString("message"));
			} else {
				// ToastUtils.show(context, jsonData.optString("message"));
			}
		}
	}

	/**
	 * 获取购物车请求
	 * 
	 * @author chenxu2 time 下午4:14:48
	 */
	private class onRequestListener extends OnRequestListenerAdapter<Object> {

		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);

			JsonData jsonData = JsonData.create(response);
			JsonData data = jsonData.optJson("shopping_cart");
			String price = jsonData.optString("total_amount");
			if (data != null && data.length() > 0) {
				ll_have_products.setVisibility(View.VISIBLE);
				ll_no_products.setVisibility(View.GONE);
				shoppingAdapter.removeAll();
				allCartsDataList.clear();
				ptr_view_cart.refreshComplete();
				clearSelectList();
				updateCheckBoxShowState(false);
				for (int i = 0; i < data.length(); i++) {
					JsonData itemData = data.optJson(i);
					String joinCount = itemData.optString("buy_count");
					String title = itemData.optString("phase");
					String name = itemData.optString("name");
					String joinNeed = itemData.optString("price");
					String pic = itemData.optString("pic");
					String num = itemData.optString("number");
					String gp_id = itemData.optString("gp_id");
					ShoppingCartsEntity shoppingCartsEntity = new ShoppingCartsEntity(
							title, name, joinNeed, joinCount, pic, num, gp_id);
					allCartsDataList.add(shoppingCartsEntity);
				}

				shoppingAdapter.replace(allCartsDataList);
				jsonArray = null;
				jsonArray = new JSONArray();

				for (ShoppingCartsEntity shoppingCartsEntity : allCartsDataList) {
					JSONObject object = new JSONObject();
					try {
						String goodnum = shoppingCartsEntity.getGoodsNum();
						String gpid = shoppingCartsEntity.getGp_id();
						int nem = Integer.parseInt(goodnum);
						int id = Integer.parseInt(gpid);
						object.put("number", nem);
						object.put("gp_id", id);
						jsonArray.put(object);

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			} else {
				ll_have_products.setVisibility(View.GONE);
				ll_no_products.setVisibility(View.VISIBLE);
			}
			if (price != null && price.length() > 0) {
				tv_goods_num.setText("共计：" + price + "" + "件");
				tv_all_money.setText("总计：" + price + "" + "元");
			}

		}

		@Override
		public void onRequestPrepare() {
			super.onRequestPrepare();

		}

		@Override
		public void onRequestFailed(String error) {
			super.onRequestFailed(error);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		Boolean hasLog = PreferenceHelper.readBoolean(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (hasLog) {
			ll_unlogin.setVisibility(View.GONE);
			userid = PreferenceHelper.readString(context,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
			// refresh shoppingcarts
			getCartsData();
		}
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		getCartsData();
		// EventFactory.sendUpdateCartCount(0);
	}

	/**
	 * 初始化下拉刷新
	 * 
	 */
	private void initPtr() {
		/* 创建自定义刷新头部view */
		ptrHeader = new PtrHeader(this);
		ptrHeader.setBackgroundColor(Color.WHITE);
		/* 设置刷新头部view */
		ptr_view_cart.setHeaderView(ptrHeader);
		/* 设置回调 */
		ptr_view_cart.addPtrUIHandler(ptrHeader);
		/* 设置下拉刷新监听 */
		ptr_view_cart.setPtrHandler(new PtrHandler() {

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				frame.postDelayed(new Runnable() {

					@Override
					public void run() {
						Boolean hasLog = PreferenceHelper.readBoolean(context,
								SPConstants.SHARED_PREFERENCE_NAME,
								SPConstants.HAS_LOGGED, false);
						if (hasLog) {
							ll_unlogin.setVisibility(View.GONE);
							userid = PreferenceHelper.readString(context,
									SPConstants.SHARED_PREFERENCE_NAME,
									SPConstants.USERID, "");
							getCartsData();
						} else {
							ll_unlogin.setVisibility(View.VISIBLE);
						}
					}
				}, 500);
			}

			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				// TODO Auto-generated method stub
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						content, header);
			}
		});
		/**
		 * 延时100秒自动刷新
		 */
		ptr_view_cart.postDelayed(new Runnable() {

			@Override
			public void run() {
				ptr_view_cart.autoRefresh();
			}
		}, 100);

	}

	/**
	 * 更新全选Checkbox的显示状态
	 */
	private void updateCheckBoxShowState(boolean mCheckedState) {
		mSelectAll.updateState(mCheckedState);
		mEditSelectAll.updateState(mCheckedState);
	}

	/**
	 * 初始化box控件
	 */
	private void initView() {
		mSelectAll.setOnCheckedChangeListener(this);
		mEditSelectAll.setOnCheckedChangeListener(this);
	}

	/**
	 * 清空选中的条目
	 */
	private void clearSelectList() {
		mSelectItemList.clear();
		// 计算总价
		computeTotalPrice();

	}

	/**
	 * 购物车列表选项选中回调
	 */
	@Override
	public void onItemSelect(int position, ShoppingCartsEntity itemData,
			Boolean isSelect) {
		if (mSelectItemList.contains(itemData)) {
			jsonArray = null;
			if (!isSelect) {
				mSelectItemList.remove(itemData);
			}
		} else {
			if (isSelect) {
				mSelectItemList.add(itemData);

			}
		}
		System.out
				.println("____________________________________________________________+"
						+ mSelectItemList);

		// 计算并显示总价
		computeTotalPrice();

		if (mSelectItemList.size() == allCartsDataList.size()) {
			updateCheckBoxShowState(true);

		} else {
			updateCheckBoxShowState(false);
		}
		// 单个商品提交
		jsonArray = null;
		jsonArray = new JSONArray();
		for (ShoppingCartsEntity shoppingCartsEntity : mSelectItemList) {
			JSONObject object = new JSONObject();
			try {
				String goodnum = shoppingCartsEntity.getGoodsNum();
				String gpid = shoppingCartsEntity.getGp_id();
				int nem = Integer.parseInt(goodnum);
				int id = Integer.parseInt(gpid);
				object.put("number", nem);
				object.put("gp_id", id);
				jsonArray.put(object);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		System.out.println("************************" + jsonArray);

		LogUtils.i("选中：" + mSelectItemList.toString());
		// 删除
		jsonArrayDelete = new JSONArray();
		for (ShoppingCartsEntity shoppingCartsEntity : mSelectItemList) {
			JSONObject object = new JSONObject();
			try {
				String gpid = shoppingCartsEntity.getGp_id();

				int id = Integer.parseInt(gpid);
				object.put("gp_id", id);
				jsonArrayDelete.put(object);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 计算总价
	 */
	private void computeTotalPrice() {
		float totalPrice = 0;// 总价
		float amountPrice = 0;// shuliang
		for (ShoppingCartsEntity shoppingCartsEntity : mSelectItemList) {
			totalPrice += Float.parseFloat(shoppingCartsEntity.getGoodsNum());
			amountPrice += Float.parseFloat(shoppingCartsEntity.getGoodsNum());
		}
		tv_goods_num.setText("共计：" + amountPrice + "" + "件");
		tv_all_money.setText("总计：" + totalPrice + "" + "元");

	}

	/**
	 * 全部选择
	 * 
	 * @param checkBox
	 * @param isChecked
	 */

	@Override
	public void onCheckedChanged(CheckBoxWithListVview buttonView,
			boolean isChecked) {
		// 同步一般状态下的全选按钮与编辑模式下全选按钮的显示
		switch (buttonView.getId()) {
		case R.id.cb_select_all_edit:
			if (mEditSelectAll.isChecked()) {
				mSelectAll.updateState(true);
			} else {
				mSelectAll.updateState(false);
			}
			break;
		case R.id.cb_selete_all:
			if (mSelectAll.isChecked()) {
				mEditSelectAll.updateState(true);

			} else {

				mEditSelectAll.updateState(false);
				jsonArray = null;

			}
			break;

		default:
			break;
		}
		// 全部选择
		if (isChecked) {

			clearSelectList();
			if (allCartsDataList != null && allCartsDataList.size() > 0) {
				for (ShoppingCartsEntity shoppingCartsEntity : allCartsDataList) {
					mSelectItemList.add(shoppingCartsEntity);

				}
				System.out
						.println("____________________________________________________________+"
								+ mSelectItemList);
				jsonArray = null;
				jsonArray = new JSONArray();

				for (ShoppingCartsEntity shoppingCartsEntity : mSelectItemList) {
					JSONObject object = new JSONObject();
					try {
						String goodnum = shoppingCartsEntity.getGoodsNum();
						String gpid = shoppingCartsEntity.getGp_id();
						int nem = Integer.parseInt(goodnum);
						int id = Integer.parseInt(gpid);
						object.put("number", nem);
						object.put("gp_id", id);
						jsonArray.put(object);

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}

			// 删除
			jsonArrayDelete = null;
			jsonArrayDelete = new JSONArray();
			for (ShoppingCartsEntity shoppingCartsEntity : mSelectItemList) {
				JSONObject object = new JSONObject();
				try {
					String gpid = shoppingCartsEntity.getGp_id();

					int id = Integer.parseInt(gpid);
					object.put("gp_id", id);
					jsonArrayDelete.put(object);

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			computeTotalPrice();
		} else {
			clearSelectList();
		}
		shoppingAdapter.notifyDataSetChanged();
	}
}
